﻿namespace NTLib.Resources
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.CompilerServices;

    /// <summary>
    /// 
    /// </summary>
    public static class ResourcesHelper
    {
        #region Fields

        private static readonly Assembly s_assembly;

        #endregion

        #region ctor

        /// <summary>
        /// Initializes a new instance of the <see cref="ImageMgr"/> class.
        /// </summary>
        static ResourcesHelper()
        {
            s_assembly = typeof(ResourcesHelper).GetTypeInfo().Assembly;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets the first embedded resource that partialy contain the name pass in parameters.
        /// </summary>
        /// <param name="name">The name.</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Stream GetEmbeddedResource(string name)
        {
            return GetEmbeddedResource(name, s_assembly);
        }

        /// <summary>
        /// Gets the first embedded resource that partialy contain the name pass in parameters.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="type">Used to define the assembly where to found the resources</param>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Stream GetEmbeddedResource(this Type type, string name)
        {

            return GetEmbeddedResource(name, type.GetTypeInfo().Assembly);
        }

        /// <summary>
        /// Gets the first embedded resource that partialy contain the name pass in parameters.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Stream GetEmbeddedResource<T>(string name)
        {
            return GetEmbeddedResource(name, typeof(T).GetTypeInfo().Assembly);
        }

        /// <summary>
        /// Gets the first embedded resource that partialy contain the name pass in parameters.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public static Stream GetEmbeddedResource(string name, Assembly assembly)
        {
            return (from resource in assembly.GetManifestResourceNames()
                    where resource.ToLowerInvariant().Contains(name.ToLowerInvariant())
                    select assembly.GetManifestResourceStream(resource)).FirstOrDefault();
        }
        #endregion
    }
}
